const gulp = require("gulp");
const concat = require("gulp-concat");
const sass = require('gulp-sass');
sass.compiler = require('node-sass');
const uglify = require('gulp-uglify');
const cleanCSS = require('gulp-clean-css');

const scriptsJson = require("./conf/index").scripts;
const scssJson = require("./conf/index").scss;

let scriptsTaskArray = [];
let scssTaskArray = [];

// 功能定义区

/**
 * @function init 初始化功能 , 编列了scripts路径还有创建了 scripts 指令;
 * @function mergeMyScripts 根据scripts 对象实现的scripts指令拆分,文件合并
 * 
 */
function init(){
    mergeMyScripts(scriptsJson);
    mergeMyScss(scssJson);
}

function mergeMyScripts(json){
    for(let attr in json){
        scriptsTaskArray.push("scripts-build-"+attr);
        gulp.task("scripts-build-"+attr,()=>{
            return gulp.src([scriptsJson[attr].src+"*.js"])
                        .pipe(concat(attr+".js"))
                        .pipe(uglify())
                        .pipe(gulp.dest("./dist/scripts"));
        })
    }
}

function mergeMyScss(json){
    for(let attr in json){
        scssTaskArray.push("scss-build-"+attr);
        gulp.task("scss-build-"+attr,()=>{
            return gulp.src([scssJson[attr].src+"*.+(scss|sass)"])
                        .pipe(concat(attr+".scss"))
                        .pipe(sass())
                        .pipe(cleanCSS({debug: true}, (details) => {
                            console.log(`${details.name}: ${details.stats.originalSize}`);
                            console.log(`${details.name}: ${details.stats.minifiedSize}`);
                        }))
                        .pipe(gulp.dest("./dist/scss"));
        })
    }
}

//指令定义区

/**
 * @task html :  转存html
 * @task default : 自动开启环境
 * 
 */

 gulp.task("html-build",()=>{
    return gulp.src(["./src/views/**/*.html"])
                .pipe(gulp.dest("./dist/views"));
 });


 gulp.task("images-build",()=>{
    return gulp.src("./src/images/**/*")
                .pipe(gulp.dest("./dist/images"));
 })

 gulp.task("scripts-build",scriptsTaskArray);
 gulp.task("scss-build",scssTaskArray);

 gulp.task("build",["html-build","scripts-build","scss-build","images-build"]);

 init();
